//
//  TCLYAddressViewController.m
//  YuErmuYing
//
//  Created by LYang on 16/8/27.
//  Copyright © 2016年 Tiancheng. All rights reserved.
//

#import "TCLYAddressViewController.h"
#import "TCLYAddAddressViewController.h"
#import "TCLYAddressView.h"
#import "TCLYAddressTableViewCell.h"
#import "TCLYBabyHomeViewController.h"
#import "TCLYMineModel.h"
#import "TCLYRegisterView.h"
#import "Macros.h"
#import "Masonry.h"
#import "TCLYUser.h"

@interface TCLYAddressViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) TCLYAddressView * addressView;
@property (nonatomic, strong) UITableView * addressTableView;
@property (nonatomic, strong) TCLYMineModel * mineModel;
@property (nonatomic, strong) NSMutableArray * BtnArr;
@property (nonatomic, assign) NSInteger accessCount;
@property (nonatomic, strong) TCLYRegisterView * registerView;
@property (nonatomic, strong) TCLYUser * user;
@end

@implementation TCLYAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createTitleView];
    self.BtnArr = [NSMutableArray array];
    self.registerView = [[TCLYRegisterView alloc] init];
    self.user = [[TCLYUser alloc] init];
    self.view.backgroundColor = bgColor;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadAddressSucceed) name:@"loadAddressSucceed" object:nil];
    self.mineModel = [[TCLYMineModel alloc] init];
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId,@"uid", nil];
    [self.mineModel loadAddressParameter:dic];
    
    // Do any additional setup after loading the view from its nib.
    [self createView];
    self.accessCount = -1;
}
-(void)createTitleView{
    self.navigationController.navigationBar.barStyle = UIBarMetricsCompactPrompt;
    self.navigationController.navigationBar.backgroundColor = statusColor;
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, -20, screenWidth, 20)];
    view.backgroundColor = navColor;
    [self.navigationController.navigationBar addSubview:view];
    
    UILabel * titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"收货地址";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.frame = CGRectMake(0, 0, 50, 20);
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.navigationItem.titleView = titleLabel;
    
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(12, 22, 20, 20);
    [leftBtn setImage:[UIImage imageNamed:@"left"] forState:UIControlStateNormal];
    leftBtn.tag = 91;
    [leftBtn addTarget:self action:@selector(statusBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
}
-(void)statusBtnAction:(id)sender{
    switch (((UIButton *)sender).tag) {
        case 91:{
            if (self.isMineAddress == NO) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"mineAddressNo" object:self];
            }
            [self.navigationController popViewControllerAnimated:YES];
            self.navigationController.navigationBarHidden = NO;
            self.tabBarController.tabBar.hidden = YES;
        }
            break;
        case 92:{
            
        }
            break;
    }
}
-(void)loadAddressSucceed{
    NSLog(@"收到通知");
    if (self.mineModel.addressArr == nil) {
        self.addressTableView.hidden = YES;
    }else if (self.mineModel.addressArr != nil){
        self.addressView.hidden = YES;
        [self.addressTableView reloadData];
    }
}
-(void) createView{
    
    UIButton * addAddressBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addAddressBtn setTitle:@"添加地址" forState:UIControlStateNormal];
    [addAddressBtn setTitleColor:btnColor forState:UIControlStateNormal];
    addAddressBtn.backgroundColor = [UIColor whiteColor];
    [addAddressBtn addTarget:self action:@selector(addAddressBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addAddressBtn];
    [addAddressBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).offset(12);
        make.right.mas_equalTo(self.view.mas_right).offset(-12);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(-50);
        make.height.mas_equalTo(46);
    }];
    self.addressView = [[TCLYAddressView alloc] init];
    self.addressView.backgroundColor = bgColor;
    [self.addressView.addressBtn addTarget:self action:@selector(addressViewAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.addressView];
    [self.addressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view);
        make.left.mas_equalTo(self.view);
        make.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(addAddressBtn.mas_top).offset(-20);
    }];
    
    self.addressTableView = [[UITableView alloc] init];
    self.addressTableView.backgroundColor = bgColor;
    [self.addressTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.addressTableView.delegate = self;
    self.addressTableView.dataSource = self;
    [self.view addSubview:self.addressTableView];
    [self.addressTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(addAddressBtn.mas_top).offset(-20);
    }];
}
//添加地址的时间按钮
-(void) addAddressBtnAction:(id)sender{
    TCLYAddAddressViewController * addAddressViewCtr = [[TCLYAddAddressViewController alloc] init];
    addAddressViewCtr.addAddressDic = nil;
    [self.navigationController pushViewController:addAddressViewCtr animated:YES];
    
}
//随便逛逛的按钮时间
-(void) addressViewAction{
    TCLYBabyHomeViewController * babyHomeViewCtr = [[TCLYBabyHomeViewController alloc] init];
    [self.navigationController pushViewController:babyHomeViewCtr animated:YES];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}
//tableView必须实现的代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.mineModel.addressArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * identifier = @"addressCell";
    TCLYAddressTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[TCLYAddressTableViewCell alloc] initWithReuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.nameLabel.text = [NSString stringWithFormat:@"收货人:  %@",self.mineModel.addressArr[indexPath.row][@"address_consignee"]];
    cell.telLabel.text = self.mineModel.addressArr[indexPath.row][@"address_consignee_pnone"];
    cell.addressLabel.text = [NSString stringWithFormat:@"收货地址:%@%@",self.mineModel.addressArr[indexPath.row][@"address_add"],self.mineModel.addressArr[indexPath.row][@"address_detail"]];
    NSLog(@"%@",self.mineModel.addressArr[indexPath.row][@"address_default"]);
    if ([self.mineModel.addressArr[indexPath.row][@"address_default"] isEqual:@"1"] || self.accessCount == indexPath.row) {
        cell.addressBtn.selected = YES;
    }else{
        cell.addressBtn.selected = NO;
    }
    cell.deleteBtn.tag = 1000+indexPath.row;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.editorBtn.tag = 3000+indexPath.row;
    [cell.editorBtn addTarget:self action:@selector(editorBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.addressBtn.tag = 5000+indexPath.row;
    [cell.addressBtn addTarget:self action:@selector(addressBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.BtnArr addObject:cell.addressBtn];
    
    return cell;
}
//改变行的高度（实现主个代理方法后 rowHeight 设定的高度无效）
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130;
}
//删除按钮的时间
-(void)deleteBtnAction:(id)sender{
    [self.registerView Prompt:@"您确定要删除此帖子吗?" Controller:self];
    self.registerView.determineAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteBtnAction) name:@"deleteAddressSucceed" object:nil];
        
        NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.mineModel.addressArr[((UIButton *)sender).tag-1000][@"address_id"],@"aid",self.user.userId,@"uid", nil];
        [self.mineModel deleteTieZiParameters:dic];
        return ;
    }];
    self.registerView.cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"quxiao");
    }];
    [self.registerView.promptAlertCtr addAction:self.registerView.determineAction];
    [self.registerView.promptAlertCtr addAction:self.registerView.cancelAction];
}
//编辑按钮的事件
-(void)editorBtnAction:(id)sender{
    TCLYAddAddressViewController * addAddressViewCtr = [[TCLYAddAddressViewController alloc] init];
    addAddressViewCtr.addAddressDic = self.mineModel.addressArr[((UIButton *) sender).tag-3000];
    [self.navigationController pushViewController:addAddressViewCtr animated:YES];
}
//设置默认的事件
-(void)addressBtnAction:(id)sender{
    ((UIButton *)sender).selected = YES;
    for (int i = 0 ; i<self.BtnArr.count; i++) {
        if (![((UIButton *)sender) isEqual:self.BtnArr[i]]) {
            UIButton * btn =  self.BtnArr[i];
            btn.selected = NO;
        }else{
            UIButton * btn =  self.BtnArr[i];
            self.accessCount = btn.tag-5000;
        }
    }
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId,@"uid",self.mineModel.addressArr[((UIButton *)sender).tag-5000][@"address_id"], @"aid", nil];
    [self.mineModel defaultAddressParameter:dic];
    NSLog(@"%ld",(unsigned long)self.BtnArr.count);
}
-(void)deleteBtnAction{
    NSLog(@"删除成功");
    [self.addressTableView reloadData];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
